@file:JvmName("TryTool")
package com.oktest.measure.kt

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.Closeable

fun doWithTry(block:()->Unit) {
    try {
        block()
    } catch (e: Exception) {
        e.printStackTrace()
    }
}

inline fun <reified T> resultTry(default: T? = null,block: () -> T): T = try {
    block()
} catch (e: Exception) {
    default?:T::class.java.newInstance()
}

fun <T> T.doWithTryReturn(block: () -> Unit): Boolean {
    try {
        block()
    } catch (e: Exception) {
        return false
    }
    return true
}

fun  Closeable?.doWithTry(block: () -> Unit) {
    try {
        block()
    } catch (e: Exception) {

    }finally {
        this?.close()
    }
}

fun <T> T.tryApply(block: (T) -> Unit) {
    try {
        block(this)
    } catch (e: Exception) {

    } finally {

    }
}
suspend inline fun successTryContext(crossinline block: () -> Unit): Boolean = try {
    withContext(Dispatchers.IO) {
        block()
        true
    }
} catch (e: Exception) {
    e.log()
    false
}


suspend inline fun <reified T> resultTryContext(crossinline block: () -> T?): T = try {
    withContext(Dispatchers.IO){
        block()?:T::class.java.newInstance()
    }
} catch (e: Exception) {
    e.log()
    T::class.java.newInstance()
}


suspend inline fun <reified T> resultListTryContext(crossinline block: () -> List<T>?): List<T> = try {
    withContext(Dispatchers.IO){
        block()?: arrayListOf()
    }
} catch (e: Exception) {
    arrayListOf()
}

fun Exception.log() {
    this.printStackTrace()
}